
import datetime
import config
import json
from utils import request
import sys
from typing import List
if sys.version_info.minor >= 8:
    from typing import Literal
else:
    from typing_extensions import Literal
'''
代码规范：
不同的操作对象，多维表格、表格、云空间等，定义为Client的子类
Client的子类，__init__方法传入操作对象的token，如Base的app_token，Sheet的doc_token
子类的Request方法中，第一个下划线前是Request的方法，如put、get、post
子类的Request方法，不再传入操作对象的token，而是在方法中通过self的属性传入
'''
class Client(object):
    def __init__(self, lark_host):
        self._host = lark_host

    def get_tenant_access_token(self, app_id, app_secret):
        url = self._host+"/open-apis/auth/v3/app_access_token/internal/"
        headers = {
            'Content-Type': 'application/json; charset=utf-8'
        }
        payload = {
            'app_id': app_id,
            'app_secret': app_secret
        }
        resp = request("POST", url, headers, payload)
        return resp['tenant_access_token']

'''
    def get_records(self, access_token: str, app_token: str, table_id: str, view_id: str=None):
        url = f"{self._host}/open-apis/bitable/v1/apps/{app_token}/tables/{table_id}/records"
        headers = {
            'Content-Type': 'application/json; charset=utf-8',
            'Authorization': 'Bearer '+access_token,
        }
        
        params = {}
        if view_id: params['view_id'] = view_id
        resp = request("GET", url, headers, params=params)
        return resp['data']['items']

    def batch_create_records(self, access_token: str, app_token: str, table_id: str, records: List[dict]):
        url = f"{self._host}/open-apis/bitable/v1/apps/{app_token}/tables/{table_id}/records/batch_create"
        headers = {
            'Content-Type': 'application/json; charset=utf-8',
            'Authorization': 'Bearer '+access_token,
        }
        payload = {
            'records': records
        }
        resp = request("POST", url, headers, payload)
        return resp['data']['records']

    def get_fields_list(self, access_token: str, app_token: str, table_id: str, view_id: str=None, page_token: str=None, page_size: int=None):
        url = f"{self._host}/open-apis/bitable/v1/apps/{app_token}/tables/{table_id}/fields"
        headers = {
            'Content-Type': 'application/json; charset=utf-8',
            'Authorization': 'Bearer '+access_token,
        }
        params = {}
        if view_id: params['view_id'] = view_id
        if page_token: params['page_token'] = page_token
        if page_size: params['page_size'] = page_size
        resp = request("GET", url, headers, params=params)
        return resp['data']

    def batch_update_records(self, access_token: str, app_token: str, table_id: str, records: List[dict], user_id_type: str=None):
        url = f"{self._host}/open-apis/bitable/v1/apps/{app_token}/tables/{table_id}/records/{record_id}"
        headers = {
            'Content-Type': 'application/json; charset=utf-8',
            'Authorization': 'Bearer '+access_token,
        }
        payload = {
            'records': records
        }
        resp = request("POST", url, headers, payload)
        return resp['data']['records']
'''   
class Sheet(Client):
    def __init__(self, _host: str, doctoken: str):
        super().__init__(_host)
        self.doctoken = doctoken
    # 下载单个范围的sheet表数据，已实装测试通过
    def get_sheet_record_single(self,access_token:str,ranges:str):
        url = f"{self._host}/open-apis/sheets/v2/spreadsheets/{self.doctoken}/values/{ranges}"
    
        headers = {
            'Authorization': 'Bearer '+access_token,
            'Content-Type': "application/json; charset=utf-8"
        }
        params = {'dateTimeRenderOption':'FormattedString'}
        resp = request("GET", url, headers,params=params)
        return resp['data']['valueRange']['values']
    
    # 更新单个范围的sheet表数据，已实装测试通过
    def put_sheet_record_single(self,access_token:str,data:list,ranges:str):
        url = f"{self._host}/open-apis/sheets/v2/spreadsheets/{self.doctoken}/values/"
        
        headers = {
            'Authorization': 'Bearer '+ access_token,
            'Content-Type': "application/json; charset=utf-8"
        }
        
        json_data = {"valueRange": {
            "range": ranges,
            "values": data
            }
        }
        resp = request("PUT", url, headers=headers, payload = json_data)
        return resp['data']['updatedRange']
    
    def batch_get_filter2(self,access_token, doctoken,sheet_id, data):
        url = f"{self._host}/open-apis/sheets/v3/spreadsheets/{doctoken}/sheets/{sheet_id}/filter_views/query"
        headers = {
            'Authorization': 'Bearer '+access_token
        }
        payload=data
        resp = request("GET", url, headers, payload)
        return resp['data']['spreadsheetToken']
    
class Base(Client):
    def __init__(self,_host,app_token):
        super().__init__(_host)
        self.app_token = app_token
        
    def get_records_list(self, 
                         access_token: str, 
                         table_id: str, 
                         view_id: str=None, 
                         page_token: str=None, 
                         page_size: int=None,
                         field_names:str = None,
                         record_filter:str = None):
        
        url = f"{self._host}/open-apis/bitable/v1/apps/{self.app_token}/tables/{table_id}/records"
        headers = {
            'Content-Type': 'application/json; charset=utf-8',
            'Authorization': 'Bearer '+access_token,
        }
        params = {}
        if view_id: params['view_id'] = view_id
        if page_token: params['page_token'] = page_token
        if page_size: params['page_size'] = page_size
        if field_names: params['field_names'] = field_names
        if record_filter: params['filter'] = record_filter
        params['display_formula_ref']=True
        params['automatic_fields']=False
        resp = request("GET", url, headers, params=params)
        return resp['data']
    
    def update_record(self,
                      access_token: str,
                      table_id: str,
                      record_id: str,
                      payload:str,
                      ):
       
        url = f"{self._host}/open-apis/bitable/v1/apps/{self.app_token}/tables/{table_id}/records/{record_id}"
        headers = {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer '+ access_token
        }
        resp = request("PUT", url, headers, data=payload)
        
        return resp['data']['field']
